package ui;

import com.hzheima.game.GameJPanel;
import com.hzheima.util.ImageUtil;
import constant.EndConstant;
import constant.PlaneConstant;
import constant.UiConstant;
import entity.*;
import entity.props.Bomb;
import entity.props.BulletBuff;
import entity.props.HealthPack;
import interaction.end.EndLogic;
import interaction.crash.EntityCrash;
import util.KeyStatesConfig;
import util.MusicUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * @Author:zhengbowen
 * @Date: 2025/09/07 9:36
 * @Description:页面ui配置
 */
public class PlaneWarPanel extends GameJPanel {
    public static BufferedImage BgImage;
    public static BufferedImage MoneyImage;
    public static BufferedImage StImage;//左括号
    public static BufferedImage EdImage;//右括号
    public static BufferedImage SuperSkillImage; // 大招图标
    public static int level=1;
    KeyStatesConfig inputManager;//键的状态
    private Timer gameTimer;//计时器管理帧率
    Plane plane1;
    Plane plane2;
    Boss boss; // BOSS实例
    Bigkill bigkill; // 大招实例
    Bomb bomb;//炸弹对象
    BulletBuff bulletBuff;//buff对象
    private boolean bossCreated; // 是否已创建BOSS

    boolean musicFlag =true;
    public PlaneWarPanel() {
        setBackground(Color.pink);
        BgImage = ImageUtil.getImg("BG.png");
        MoneyImage = ImageUtil.getImg("Money.png");
        StImage = ImageUtil.getImg("st.png");
        EdImage = ImageUtil.getImg("ed.png");
        plane1 = new Plane(PlaneConstant.player1Id);
        plane2 = new Plane(PlaneConstant.player2Id);
        bigkill = new Bigkill();
        boss = null;
        //炸弹对象
        bomb = new Bomb();
        //buff
        bulletBuff = new BulletBuff();
        bossCreated=false;
        // 加载大招图标
        SuperSkillImage = ImageUtil.getImg("大招.png");
        //设置键盘状态检测
        inputManager = new KeyStatesConfig(this);
        //设置帧率,60帧率
        setupGameLoop();
    }

    @Override
    public void paint(Graphics g) {
        //绘制背景
        drawBackground(g);
        drawEntity(g);
        // 分数达到要求游戏胜利
        EndLogic.gameWinUi(g);
        // 游戏结束
        EndLogic.gameOverUi(g);
    }

    private void drawEntity(Graphics g) {
        // 绘制大招进度条和图标
        drawSuperSkillProgress(g,plane1);
        drawSuperSkillProgress(g,plane2);
        //画飞机
        drawPlane(plane1, g);
        drawPlane(plane2, g);
        //画buff
        for (int i = 0; i < Bomb.bombs.size(); i++) {
            Bomb bomb = Bomb.bombs.get(i);
            bomb.rebound();
            bomb.draw(g);
        }
        for (int i = 0; i < BulletBuff.bulletBuffs.size(); i++) {
            BulletBuff bulletBuff = BulletBuff.bulletBuffs.get(i);
            bulletBuff.rebound();
            bulletBuff.draw(g);
        }
        //画小球
        for (int i = 0; i < Ball.balls.size(); i++) {
            Ball oneBall = Ball.balls.get(i);
            oneBall.rebound();
            oneBall.draw(g);
        }
        // 画血包
        for (HealthPack pack : HealthPack.healthPacks) {
            pack.draw(g);
        }
        // 画BOSS和BOSS子弹
        if (boss != null) {
            boss.draw(g);
            ArrayList<Bullet> tempBossBullets = new ArrayList<>(boss.bossBullets);
            for (Bullet bossBullet : tempBossBullets) {
                bossBullet.draw(g);
            }
        }
        if (bigkill != null) {
            bigkill.draw(g);
        }
    }

    private  void drawBackground(Graphics g) {
        //画背景
        g.drawImage(BgImage, 0, 0, UiConstant.APP_WIDTH, UiConstant.APP_HEIGHT, null);
        //画分数
        g.setFont(new Font("楷体", Font.BOLD, 25));
        //设置字体颜色
        g.setColor(Color.red);
        g.drawString("分数：" + EntityCrash.score, 30, 30);
        //画金币
        g.drawImage(MoneyImage, 300, 5, 30, 30, null);
        g.drawString("0.00k", 350, 30);
        //画历史最高
        g.drawString("历史最高：0.00k", 300, 60);
        //画关卡名
        g.setFont(new Font("楷体", Font.PLAIN, 30));
        g.drawString("关卡1", 25, 60);
        //画矩形 绘制左括号
        g.drawImage(StImage, 15, 80, 5, 25, null);
        //分数
        int progress = EntityCrash.score / 50;
        int endProgress = EndConstant.END_SCORE / 50;
        //画矩形 设置画笔的颜色
        g.setColor(Color.GRAY);
        for (int i = 0; i < endProgress; i++) {
            g.fillRect(25 + i * (10 + 5), 80, 10, 25);
        }
        //画矩形,蓝色(动态)
        EndLogic.win(EntityCrash.score);
        g.setColor(Color.cyan);
        for (int i = 0; i < progress; i++) {
            g.fillRect(25 + i * (10 + 5), 80, 10, 25);
        }
        //画右括号
        g.drawImage(EdImage, UiConstant.APP_WIDTH - (25 + 10), 80, 5, 25, null);
        // 画能量条框架
        drawEnergyBarFrame(g,plane1);
        drawEnergyBarFrame(g,plane2);

    }

    //画飞机的逻辑
    public void drawPlane(Plane plane, Graphics g) {
        //闪烁检测
        plane.openFlash(g,plane);
        //画血量
        drawPlaneHealth(g, plane);
        //画子弹
        ArrayList<Bullet> bullets = plane.getBullets();
        for (int i = 0; i < bullets.size(); i++) {
            Bullet bullet = bullets.get(i);
            bullet.draw(g);
        }
    }
    //绘制能量条框架
    private  void drawEnergyBarFrame(Graphics g,Plane plane) {

        g.drawImage(StImage, 15, 80, 5, 25, null);

        if (plane.getPlayer()==1) {
            g.setColor(Color.GRAY);
            for (int i = 0; i < Plane.MAX_ENERGY; i++) {
                g.fillRect(25 + i * (10 + 5), 120, 5, 17);
            }
            g.setColor(Color.yellow);
            for (int i = 0; i <plane.getSuperSkillEnergy(); i++) {
                g.fillRect(25 + i * (10 + 5), 120, 10, 25);
            }
        }
        if (plane.getPlayer()==2) {
            g.setColor(Color.GRAY);
            for (int i = 0; i < Plane.MAX_ENERGY; i++) {
                g.fillRect(UiConstant.APP_WIDTH-50 - i * (10 + 5), 120, 5, 17);
            }
            g.setColor(Color.yellow);
            for (int i = 0; i <plane.getSuperSkillEnergy(); i++) {
                g.fillRect(UiConstant.APP_WIDTH-50 - i * (10 + 5), 120, 10, 25);
            }
        }
        g.drawImage(EdImage, UiConstant.APP_WIDTH - (25 + 10), 80, 5, 25, null);
    }

    //每三十秒发射子弹
    @Override
    public void run() {
        if (!EndLogic.gameOver) {
            Ball.createBall();
            Ball.ballsMove();
            BulletBuff.createBuff();
            BulletBuff.buffMove();
            Bomb.createBomb();//创建炸弹
            Bomb.bombMove();//炸弹移动
            planeRunLogic(plane1);
            planeRunLogic(plane2);
            // 生成血包
            HealthPack.createHealthPack();
            HealthPack.HealthPackMove();
        } else {
            if (!EndLogic.restartGame()) {
                playBGMusic();
                Ball.balls.clear();
                EntityCrash.bulletBuffss.clear();
                bossCreated=false;
                boss=null;
                BulletBuff.bulletBuffs.clear();
                HealthPack.healthPacks.clear();
                Bomb.bombs.clear();
                Plane.bullets.clear();
                plane1 = new Plane(PlaneConstant.player1Id);
                plane2 = new Plane(PlaneConstant.player2Id);
                System.out.println(plane1.getLevel());
                System.out.println(plane2.getLevel());
            }

        }
        //重绘
        repaint();
    }

    private void planeRunLogic(Plane plane) {

        //判断是否打中Boss
        EntityCrash.isShootBoss(boss,plane);
        if (!Boss.bossLiveStatus){
            boss=null;
        }
        //判断是否捡到炸弹
        EntityCrash.isEatBomb(plane);
        //判断是否拿到buff
        EntityCrash.isEatBuff(plane);
        //判断是否被击毁
        EntityCrash.isCrash(plane);
        //判断球是否被打中
        EntityCrash.isShootBall(plane);
        //判断飞机是否被Boss攻击
        EntityCrash.isShootPlane(boss, plane);
        //每隔300ms发射一颗子弹
        plane.shoot();
        //判断血包与飞机的碰撞
        EntityCrash.isCrashHealthPack(plane);
    }
    //播放bgm
    private void playBGMusic() {
        if(level==2&&musicFlag)
        {
            MusicUtil.loopPlayMusic("8553.wav");
            musicFlag=false;
        }
    }
    //设置帧率
    private void setupGameLoop() {
        gameTimer = new Timer(16, e -> {
            if (!EndLogic.gameOver)
                updatePlaneState();
            repaint();
        });
        gameTimer.start();
    }

    //更新飞机状态
    private void updatePlaneState() {
        if (!EndLogic.gameOver) {
            updateGameObjects();
            handleSpecialEvents();
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_A)) {
                plane1.moveLeft();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_D)) {
                plane1.moveRight();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_W)) {
                plane1.moveUp();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_S)) {
                plane1.moveDown();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_LEFT)) {
                plane2.moveLeft();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_RIGHT)) {
                plane2.moveRight();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_UP)) {
                plane2.moveUp();
            }
            if (KeyStatesConfig.isKeyPressed(KeyEvent.VK_DOWN)) {
                plane2.moveDown();
            }
            if(KeyStatesConfig.isKeyPressed(KeyEvent.VK_J)){
                if (plane1.useSuperSkill() && bigkill != null) {
                    bigkill.activate(plane1);
                }
            }
            if(KeyStatesConfig.isKeyPressed(KeyEvent.VK_0)){
                if (plane2.useSuperSkill() && bigkill != null) {
                    bigkill.activate(plane2);
                }
            }
        }
    }

    //画飞机血量
    private void drawPlaneHealth(Graphics g, Plane plane) {
        //画飞机血量,
        // 心形血量显示
        g.setFont(new Font("楷体", Font.BOLD, 20));
        g.setColor(Color.WHITE);

        int currentHealth = plane.getCurrentBlood();
        int totalHealth = plane.getBlood();

        // 画心形血量
        for (int i = 0; i < totalHealth; i++) {
            if (i < currentHealth) {
                g.setColor(Color.RED); // 有血量-红色
            } else {
                g.setColor(Color.GRAY); // 无血量-灰色
            }
            if (plane.getPlayer() == 1)
                drawHeart(g, 10, 150 + i * 25, 8);
            if (plane.getPlayer() == 2)
                drawHeart(g, UiConstant.APP_WIDTH-35, 150 + i * 25, 8);
        }
    }

    // 添加绘制心形的方法
    private void drawHeart(Graphics g, int centerX, int centerY, int size) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 使用心形参数方程
        int points = 100; // 采样点数量
        int[] xPoints = new int[points];
        int[] yPoints = new int[points];

        for (int i = 0; i < points; i++) {
            double t = 2 * Math.PI * i / points;
            // 心形参数方程
            double x = 16 * Math.pow(Math.sin(t), 3);
            double y = 13 * Math.cos(t) - 5 * Math.cos(2*t) - 2 * Math.cos(3*t) - Math.cos(4*t);

            // 缩放并移动到中心点
            xPoints[i] = centerX + (int)(x * size / 16);
            yPoints[i] = centerY - (int)(y * size / 16); // 注意y轴方向
        }

        g2d.fillPolygon(xPoints, yPoints, points);
    }
    //绘制大招进度条和图标

    private void drawSuperSkillProgress(Graphics g,Plane plane) {
        if (plane != null) {
            // 绘制大招能量条背景
            g.setColor(new Color(64, 64, 64, 200)); // 半透明灰色背景
            g.fillRect(200, UiConstant.APP_HEIGHT - 35, 260, 30);

            // 绘制大招能量条边框
            g.setColor(Color.white);
            g.drawRect(200, UiConstant.APP_HEIGHT - 35, 260, 30);

            // 获取能量值
            int currentEnergy = plane.getSuperSkillEnergy();
            int maxEnergy = plane.getMaxEnergy();

            // 绘制当前能量
            if (maxEnergy > 0) {
                // 根据能量百分比改变颜色
                int percentage = (int) (((double) currentEnergy / maxEnergy) * 100);
                if (percentage < 30) {
                    g.setColor(Color.red);
                } else if (percentage < 70) {
                    g.setColor(Color.RED);
                } else {
                    g.setColor(Color.BLUE);
                }

                int energyWidth = (int) (((double) currentEnergy / maxEnergy) * 256);
                if (energyWidth > 0) {
                    g.fillRect(22, UiConstant.APP_HEIGHT - 33, energyWidth, 26);
                }
            }

            // 绘制文字
            g.setColor(Color.white);
            g.setFont(new Font("楷体", Font.BOLD, 14));
            g.drawString("大招能量", 25, UiConstant.APP_HEIGHT - 15);

            // 绘制百分比
            int percentage = maxEnergy > 0 ? (int) (((double) currentEnergy / maxEnergy) * 100) : 0;
            String percentageText = percentage + "%";
            FontMetrics fm = g.getFontMetrics();
            int textWidth = fm.stringWidth(percentageText);
            g.drawString(percentageText, 280 - textWidth, UiConstant.APP_HEIGHT - 15);

            // 绘制大招图标
            drawSuperSkillIcon(g, currentEnergy, maxEnergy);
        }
    }
    //绘制大招图标闪烁效果

    private void drawSuperSkillIcon(Graphics g, int currentEnergy, int maxEnergy) {
        if (SuperSkillImage != null) {
            // 如果能量满了，让图标闪烁
            if (currentEnergy >= maxEnergy) {
                // 闪烁效果
                int blink = (int) (System.currentTimeMillis() / 200) % 2;
                if (blink == 0) {
                    g.drawImage(SuperSkillImage, UiConstant.APP_WIDTH/2 - 20, UiConstant.APP_HEIGHT/2 - 20, 40, 40, null);
                }
            } else {
                g.drawImage(SuperSkillImage, 20, UiConstant.APP_HEIGHT - 70, 40, 40, null);
            }
        } else {
            // 如果没有图标，绘制一个默认的图标
            drawDefaultSuperSkillIcon(g, currentEnergy, maxEnergy);
        }
    }


    //绘制默认大招图标
    private void drawDefaultSuperSkillIcon(Graphics g, int currentEnergy, int maxEnergy) {
        if (currentEnergy >= maxEnergy) {
            // 满能量时在屏幕中央显示
            g.setColor(Color.yellow);
            g.fillOval(UiConstant.APP_WIDTH/2 - 20, UiConstant.APP_HEIGHT/2 - 20, 40, 40);
            g.setColor(Color.BLUE);
            g.setFont(new Font("楷体", Font.BOLD, 12));
            g.drawString("J", UiConstant.APP_WIDTH/2 - 5, UiConstant.APP_HEIGHT/2 + 5);
        } else {
            // 未满能量时在左下角显示
            g.setColor(Color.yellow);
            g.fillOval(20, UiConstant.APP_HEIGHT - 30, 40, 40);
            g.setColor(Color.BLUE);
            g.setFont(new Font("楷体", Font.BOLD, 12));
            g.drawString("J", 35, UiConstant.APP_HEIGHT - 45);
        }
    }
    private void updateGameObjects() {
        // 更新BOSS
        if (boss != null) {
            boss.move();
            boss.shoot();
        }

        // 更新大招
        if (bigkill != null) {
            bigkill.update();
        }
    }
    private void handleSpecialEvents() {
        // 创建BOSS
        createBossIfNeeded();
// 检查大招清屏
        checkSuperSkillClearScreen();
    }
    private void createBossIfNeeded() {
        if (!bossCreated && EntityCrash.score >= EndConstant.END_SCORE/2) { // 当分数达到100时创建BOSS
            boss = new Boss();
            bossCreated = true;
        }
    }
    //大招清屏效果
    private void checkSuperSkillClearScreen() {
        if (bigkill != null && bigkill.shouldClearScreen()) {
            // 清除所有球体
            Ball.balls.clear();
            // 清除BOSS子弹
            if (boss != null) {
                boss.bossBullets.clear();
            }
            // 清除飞机子弹
            if (plane1 != null) {
                plane1.getBullets().clear();
            }
            // 清除飞机子弹
            if (plane2 != null) {
                plane2.getBullets().clear();
            }
            // 清除清屏标记
            bigkill.clearScreenFlag();
            // 增加分数
            EntityCrash.score += 100;
        }
    }

}
